import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/ui/my/order/my_order_list_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 我的订单列表页面
/// @author tangzhentao
/// @created at 21:32 2024/12/14

class MyOrderListPage extends StatefulWidget {
  final String orderType;
  final String? orderStatus;
  final Function(MyOrderListViewmodel)? onInit;

  const MyOrderListPage({super.key, required this.orderType, required this.orderStatus, this.onInit});

  @override
  State<StatefulWidget> createState() => MyOrderListState();
}

class MyOrderListState extends State<MyOrderListPage> with AutomaticKeepAliveClientMixin {
  late final MyOrderListViewmodel _listViewmodel;

  @override
  void initState() {
    _listViewmodel = MyOrderListViewmodel(ApiOrder.list, widget.orderType, widget.orderStatus);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<MyOrderListViewmodel>(
        model: _listViewmodel,
        onInit: (data) {
          widget.onInit?.call(data);
          data.firstLoad();
        },
        builder: (ctx, order) => SmartRefresher(
          controller: order.controller,
          enablePullDown: true,
          enablePullUp: true,
          onRefresh: order.refresh,
          onLoading: order.loadMore,
          child: ListView.builder(
              itemCount: order.list.length,
              itemBuilder: (_, index) {
                final model = order.list[index];
                final isLast = index == order.list.length - 1;
                final orderNo = model.orderNo?? '';
                final productName = model.detail?.product?.name?? '';
                final quantity = model.quantity?.toString()?? '1';
                final createdAt = model.createdAt?? '';
                return GestureDetector(
                  onTap: () => order.toDetailPage(index),
                  child: Container(
                    decoration: white10Decoration,
                    margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, isLast ? XfgSize().bottomBarHeight:0),
                    child: Column(
                      children: [
                        Container(
                          height: XfgSize().size49,
                          padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
                          child: Row(
                            children: [
                              Expanded(child: XfgText('订单号:$orderNo', fontSize: XfgSize().text14, color: XfgColor.text1)),
                              XfgText(_getStatusString(model.status?? ''), fontSize: XfgSize().text16, color: model.status == OrderStatus.done ? XfgColor.text3:XfgColor.theme, bold: FontWeight.bold)
                            ],
                          ),
                        ),
                        strokeHeightContainer,
                        Padding(
                          padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().size8),
                          child: SizedBox(
                            height: XfgSize().size84,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                HttpImage(model.detail?.product?.coverImage, size: Size.square(XfgSize().size78), radius: BorderRadius.circular(XfgSize().size6)),
                                SizedBox(width: XfgSize().size12),
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Expanded(child: XfgText(productName, fontSize: XfgSize().text14, color: XfgColor.text1D, height: 1.5, maxLines: 2)),
                                          Container(
                                            width: XfgSize().size34,
                                            alignment: Alignment.centerRight,
                                            child: XfgText('x$quantity', fontSize: XfgSize().text14, color: XfgColor.text1D),
                                          )
                                        ],
                                      ),
                                      XfgText(createdAt, fontSize: XfgSize().text12, color: XfgColor.text3),
                                      _getTotalPriceWidget(model)
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                        strokeHeightContainer,
                        _getPayWidget(model),
                        Padding(
                          padding: EdgeInsets.only(left: XfgSize().size14, right: XfgSize().size10),
                          child: Row(
                            children: [
                              Expanded(child: XfgText('共$quantity件商品', fontSize: XfgSize().text14, color: XfgColor.text3)),
                              ..._handleButtons(order, model.status, model.refundStatus, index)
                            ],
                          ),
                        ),
                        _getBottomWidget(model, order, index)
                      ],
                    ),
                  ),
                );
              }
          ),
        )
    );
  }

  @override
  bool get wantKeepAlive => true;

  /// 获取状态描述
  String _getStatusString(String? status) {
    if (status == OrderStatus.paying) {
      return '待付款';
    } else if (status == OrderStatus.sending) {
      return '待发货';
    } else if (status == OrderStatus.receiving) {
      return '待收货';
    } else if (status == OrderStatus.reviewing) {
      return '待评价';
    } else if (status == OrderStatus.done) {
      return '已完成';
    } else if (status == OrderStatus.cancel) {
      return '已取消';
    } else if (status == OrderStatus.authorized) {
      return '已授权';
    } else {
      return '';
    }
  }

  /// 获取总价格描述Widget
  Widget _getTotalPriceWidget(OrderModel model) {
    if (_listViewmodel.orderType == ProductType.points) {
      /// 积分商品价格和积分
      final price = ((model.totalPrice?? 0.0) + (model.freight?? 0.0));
      final points = (model.detail?.product?.pointsPrice?? 0) * (model.quantity?? 1);
      final List<InlineSpan> children = [];
      if (price > 0) {
        final prices = price.toStringAsFixed(2).split('.');
        children.addAll([
          TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
          TextSpan(text: prices.last),
        ]);
      }
      children.addAll([
        TextSpan(text: '${price > 0 ? ' + ':''}$points', style: TextStyle(fontSize: XfgSize().text18)),
        TextSpan(text: '积分'),
      ]);
      return XfgText(price > 0 ? '¥':'', fontSize: XfgSize().text12, color: XfgColor.text1D, children: children);
    } else {
      /// 普通商品/黄金投资 价格和积分
      final prices = (((model.totalPrice?? 0.0) + (model.freight?? 0.0))).toStringAsFixed(2).split('.');
      final point = model.rewardPoints?? 0;
      final pointStr = point > 0 ? '$point积分':'';
      return Row(
        children: [
          XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.text1D, children: [
            TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
            TextSpan(text: prices.last),
          ]),
          Visibility(
            visible: pointStr.isNotEmpty,
            child: Container(
              margin: EdgeInsets.only(left: XfgSize().size16),
              height: XfgSize().size18,
              width: XfgSize().size12 + boundingTextSize(pointStr, style: TextStyle(fontSize: XfgSize().text12)).width,
              alignment: Alignment.center,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(XfgSize().size2), border: Border.all(color: XfgColor.text3, width: XfgSize().size0_5)),
              child: XfgText(pointStr, fontSize: XfgSize().text12, color: XfgColor.text3),
            ),
          )
        ],
      );
    }
  }

  /// 获取支付描述Widget
  Widget _getPayWidget(OrderModel model) {
    final List<Widget> children = [];
    if (_listViewmodel.orderType == ProductType.points) {
      /// 积分商品
      final price = ((model.totalPrice?? 0.0) + (model.freight?? 0.0));
      final points = model.pointsNum?? 0;
      final List<InlineSpan> textSpans = [];
      if (price > 0) {
        final prices = price.toStringAsFixed(2).split('.');
        textSpans.addAll([
          TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
          TextSpan(text: prices.last, style: TextStyle(fontSize: XfgSize().text16)),
        ]);
      }
      textSpans.addAll([
        TextSpan(text: '${price > 0 ? ' + ':''}$points', style: TextStyle(fontSize: XfgSize().text20)),
        TextSpan(text: '积分', style: TextStyle(fontSize: XfgSize().text16)),
      ]);
      children.addAll([
        XfgText('实际支付', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
        SizedBox(width: XfgSize().size8),
        XfgText(price > 0 ? '¥':'', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold, children: textSpans),
      ]);
    } else {
      /// 普通商品/黄金投资
      final prices = (((model.payPrice?? 0.00) + (model.amountNum?? 0.00)).toStringAsFixed(2)).split('.');
      final points = (model.pointsNum?.toDouble().toStringAsFixed(2)?? '0.00').split('.');
      children.addAll([
        XfgText('实际支付', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
        SizedBox(width: XfgSize().size8),
        XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold, children: [
          TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
          TextSpan(text: prices.last, style: TextStyle(fontSize: XfgSize().text16)),
        ]),
        SizedBox(width: XfgSize().size16),
        XfgText('积分抵扣', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
        SizedBox(width: XfgSize().size8),
        XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold, children: [
          TextSpan(text: '${points.first}.', style: TextStyle(fontSize: XfgSize().text20)),
          TextSpan(text: points.last, style: TextStyle(fontSize: XfgSize().text16)),
        ]),
      ]);
    }
    return Padding(
        padding: EdgeInsets.fromLTRB(0, XfgSize().size22, XfgSize().size18, XfgSize().size16),
        child: Row(mainAxisAlignment: MainAxisAlignment.end, children: children)
    );
  }

  /// 获取处理按钮
  List<Widget> _handleButtons(MyOrderListViewmodel order, String? status, int? refundStatus, int index) {
    final List<Widget> children = [];
    switch (status) {
      case OrderStatus.paying:
        children.addAll([
          TextButton(
              onPressed: () => order.cancelOrder(index),
              style: _buttonStyle(XfgColor.colorF2),
              child: XfgText('取消订单', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
          ),
          SizedBox(width: XfgSize().size8),
          TextButton(
              onPressed: () => order.toPay(index),
              style: _buttonStyle(XfgColor.theme),
              child: XfgText('去付款', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
          ),
        ]);
        break;
      case OrderStatus.sending:
        String text = '申请退款';
        if (refundStatus == RefundStatus.applying) {
          text = '退款中';
        } else if (refundStatus == RefundStatus.refused) {
          text = '拒绝退款';
        } else if (refundStatus == RefundStatus.refunded) {
          text = '已退款';
        }
        children.add(TextButton(
            onPressed: text.isEmpty ? null:() => order.handleRefund(index),
            style: _buttonStyle(XfgColor.theme),
            child: XfgText(text, fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
        ));
        break;
      case OrderStatus.receiving:
        if (_listViewmodel.orderType == ProductType.gold) {
          print.call('黄金 待提货');
          children.addAll([
            TextButton(
                onPressed: () => order.authorizationToCollect(index),
                style: _buttonStyle(XfgColor.colorF2),
                child: XfgText('授权代取', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
            ),
            SizedBox(width: XfgSize().size8),
            TextButton(
                onPressed: () => order.pickupGoods(index),
                style: _buttonStyle(XfgColor.theme),
                child: XfgText('我要提货', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
            ),
          ]);
        } else {
          children.addAll([
            TextButton(
                onPressed: () => order.checkLogistics(index),
                style: _buttonStyle(XfgColor.colorF2),
                child: XfgText('查看物流', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
            ),
            SizedBox(width: XfgSize().size8),
            TextButton(
                onPressed: () => order.confirmReceipt(index),
                style: _buttonStyle(XfgColor.theme),
                child: XfgText('确认收货', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
            ),
          ]);
        }
        break;
      // case OrderStatus.done:
      //   children.add(TextButton(
      //       onPressed: () => order.applyForMakingInvoice(index),
      //       style: _buttonStyle(XfgColor.colorF2),
      //       child: XfgText('申请开票', fontSize: XfgSize().text14, color: XfgColor.text3, bold: FontWeight.bold)
      //   ));
      //   break;
      case OrderStatus.reviewing:
        children.add(TextButton(
            onPressed: () => order.goReview(index),
            style: _buttonStyle(XfgColor.theme),
            child: XfgText('去评价', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
        ));
        break;
      case OrderStatus.cancel:
        children.addAll([
          TextButton(
              onPressed: () => order.deleteOrder(index),
              style: _buttonStyle(XfgColor.colorF2),
              child: XfgText('删除订单', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
          ),
          SizedBox(width: XfgSize().size8),
          TextButton(
              onPressed: () => order.buyAgain(index),
              style: _buttonStyle(XfgColor.theme),
              child: XfgText('再次购买', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
          ),
        ]);
        break;
      case OrderStatus.authorized:
        children.add(TextButton(
            onPressed: () => order.confirmReceipt(index),
            style: _buttonStyle(XfgColor.theme),
            child: XfgText('确认收货', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
        ),);
        break;
    }
    return children;
  }

  /// 获取底部Widget
  Widget _getBottomWidget(OrderModel model, MyOrderListViewmodel viewModel, int index) {
    if (model.status == OrderStatus.receiving) {
      String expressDes = model.express?.expressDetail?.expTextName?? '';
      final expressStatus = getExpressStatusDesc(model.express?.expressDetail?.status);
      final list = model.express?.expressDetail?.data;
      if (list?.isNotEmpty == true) {
        expressDes = '$expressDes：${list?.isNotEmpty == true ? list!.first.context?? '':''}';
      }
      return GestureDetector(
        onTap: () => viewModel.checkLogistics(index),
        behavior: HitTestBehavior.opaque,
        child: Container(
          margin: EdgeInsets.fromLTRB(XfgSize().size5, XfgSize().size8, XfgSize().size10, XfgSize().size5),
          padding: EdgeInsets.only(left: XfgSize().size10, right: XfgSize().size8),
          height: XfgSize().size28,
          decoration: BoxDecoration(color: XfgColor.background, borderRadius: BorderRadius.circular(XfgSize().size2)),
          child: Row(
            children: [
              Image.asset(Res.imagesOrderLogistics, width: XfgSize().size20, height: XfgSize().size15 + XfgSize().size0_5),
              XfgText(' $expressStatus ', fontSize: XfgSize().text12, color: XfgColor.orderLogistics),
              Expanded(child: XfgText(expressDes, fontSize: XfgSize().text12, color: XfgColor.color4F, maxLines: 1, overflow: TextOverflow.ellipsis))
            ],
          ),
        ),
      );
    } else if (model.status == OrderStatus.authorized) {
      return Container(
        margin: EdgeInsets.fromLTRB(XfgSize().size5, XfgSize().size5, XfgSize().size10, XfgSize().size10),
        padding: EdgeInsets.only(left: XfgSize().size10, right: XfgSize().size8),
        height: XfgSize().size28,
        child: Row(
          children: [
            XfgText('授权人', fontSize: XfgSize().text12, color: XfgColor.text3),
            SizedBox(width: XfgSize().size22),
            XfgText('张珊', fontSize: XfgSize().text12, color: XfgColor.text1D),
          ],
        ),
      );
    }

    return SizedBox(height: XfgSize().size10);
  }

  /// 刷新订单类型
  void refreshOrderType(String orderType) {
    if (orderType != _listViewmodel.orderType) {
      _listViewmodel.orderType = orderType;
      if (mounted) _listViewmodel.firstLoad();
    }
  }

  /// 按钮 装饰器
  ButtonStyle _buttonStyle(Color color) => ButtonStyle(
      backgroundColor: WidgetStatePropertyAll(color),
      shape: WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.circular(XfgSize().size31))),
      fixedSize: WidgetStatePropertyAll(Size(XfgSize().size97, XfgSize().size31))
  );
}
